using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using Avalonia.VisualTree;
using DesktopApp.Views;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Input.Platform;
using Avalonia.Controls;
using System.Diagnostics;

namespace DesktopApp.ViewModels.Services
{
    public class LogFileService : ILogFileService
    {
        public async Task<string?> OpenLogAsync()
        {
            var mainWindow = GetMainWindow();
            if (mainWindow == null) return null;

            var topLevel = TopLevel.GetTopLevel(mainWindow);
            if (topLevel == null)
            {
                Console.WriteLine("Error: Could not get TopLevel from MainWindow.");
                return null;
            }

            var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
            {
                Title = "选择日志文件",
                AllowMultiple = false,
                FileTypeFilter = new[] { new FilePickerFileType("Log Files") { Patterns = new[] { "*.log", "*.txt", "*.*" } } }
            });

            if (files.Count >= 1)
            {
                try
                {
                    await using var stream = await files[0].OpenReadAsync();
                    using var reader = new System.IO.StreamReader(stream, Encoding.UTF8); // Specify encoding
                    return await reader.ReadToEndAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error opening file: {ex.Message}");
                    // TODO: Show error message to user
                    return null;
                }
            }
            return null;
        }

        public async Task<string?> PasteLogAsync()
        {
            var mainWindow = GetMainWindow();
            if (mainWindow == null) return null;
            var topLevel = TopLevel.GetTopLevel(mainWindow);
            var clipboard = topLevel?.Clipboard;

            if (clipboard == null)
            {
                Console.WriteLine("Error: Clipboard service not available.");
                // TODO: Show error message to user
                return null;
            }
            return await clipboard.GetTextAsync();
        }

        public async Task<bool> SaveResultAsync(string resultText)
        {
            var mainWindow = GetMainWindow();
            if (mainWindow == null) return false;

            var topLevel = TopLevel.GetTopLevel(mainWindow);
             if (topLevel == null)
            {
                Console.WriteLine("Error: Could not get TopLevel from MainWindow.");
                return false;
            }

            var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
            {
                Title = "保存处理结果",
                SuggestedFileName = $"processed_log_{DateTime.Now:yyyyMMdd_HHmmss}.log",
                DefaultExtension = "log",
                FileTypeChoices = new[] { new FilePickerFileType("Log Files") { Patterns = new[] { "*.log", "*.txt" } } }
            });

            if (file != null)
            {
                try
                {
                    await using var stream = await file.OpenWriteAsync();
                    await using var writer = new System.IO.StreamWriter(stream, Encoding.UTF8); // Specify encoding
                    await writer.WriteAsync(resultText);
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error saving file: {ex.Message}");
                    // TODO: Show error message to user
                    return false;
                }
            }
            return false;
        }

        public async Task<bool> CopyTextToClipboardAsync(string textToCopy)
        {
            var mainWindow = GetMainWindow();
            if (mainWindow == null) return false;
            var topLevel = TopLevel.GetTopLevel(mainWindow);
            var clipboard = topLevel?.Clipboard;

            if (clipboard != null && !string.IsNullOrEmpty(textToCopy))
            {
                try
                {
                    await clipboard.SetTextAsync(textToCopy);
                    Debug.WriteLine("Text copied to clipboard via LogFileService.");
                    return true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error copying to clipboard: {ex.Message}");
                    // TODO: Show error message to user
                    return false;
                }
            }
            else
            {
                 Debug.WriteLine("Clipboard access failed or text to copy is empty.");
                 return false;
            }
        }

        private static Window? GetMainWindow()
        {
            if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                return desktop.MainWindow;
            }
            // Handle other lifetimes if necessary, or return null
            return null;
        }
    }
} 